<template>
  <div class="app-layout">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="container header-container">
        <div class="header-left">
          <!-- logo和网站名称 -->
          <router-link to="/" class="logo">
            <img src="../assets/logo.png" alt="Logo" class="logo-img">
            <span class="site-name">图文发布系统</span>
          </router-link>
          
          <!-- 导航链接 -->
          <nav class="main-nav">
            <router-link to="/" class="nav-link">首页</router-link>
            <el-dropdown trigger="click" @command="handleCategoryClick">
              <span class="nav-link">分类 <el-icon><arrow-down /></el-icon></span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="category in categories" :key="category.id" :command="category.id">
                    {{ category.name }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <router-link to="/announce" class="nav-link">公告</router-link>
            <router-link to="/feedback" class="nav-link">用户反馈与举报</router-link>
          </nav>
        </div>
        
        <div class="header-right">
          <!-- 搜索框 -->
          <div class="search-box">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索内容" 
              class="search-input"
              @keyup.enter="handleSearch">
              <template #suffix>
                <el-icon class="search-icon" @click="handleSearch"><search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <!-- 未登录状态 -->
          <div class="user-actions" v-if="!isLoggedIn">
            <el-button type="primary" plain size="small" @click="handleLogin">登录</el-button>
            <el-button type="primary" size="small" @click="handleRegister">注册</el-button>
          </div>
          
          <!-- 已登录状态 -->
          <div class="user-actions" v-else>
            <el-button type="primary" @click="handlePublish">发布图文</el-button>
            
            <el-dropdown trigger="click" @command="handleUserCommand">
              <div class="user-info">
                <el-avatar :size="32" :src="userAvatar"></el-avatar>
                <span class="username">{{ username }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人主页</el-dropdown-item>
                  <el-dropdown-item command="settings">账号设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </header>
    
    <!-- 主要内容区域 -->
    <main class="app-main">
      <slot></slot>
    </main>
    
    <!-- 底部页脚 -->
    <footer class="app-footer">
      <div class="container">
        <div class="footer-content">
          <div class="footer-logo">
            <img src="../assets/logo.png" alt="Logo" class="logo-img">
            <div class="site-name">图文发布系统</div>
          </div>
          
          <div class="footer-links">
            <div class="link-group">
              <h4>关于我们</h4>
              <a href="#">平台介绍</a>
              <a href="#">团队介绍</a>
              <a href="#">联系我们</a>
            </div>
            
            <div class="link-group">
              <h4>帮助中心</h4>
              <a href="#">用户指南</a>
              <a href="#">常见问题</a>
              <a href="#">意见反馈</a>
            </div>
            
            <div class="link-group">
              <h4>法律声明</h4>
              <a href="#">用户协议</a>
              <a href="#">隐私政策</a>
              <a href="#">版权声明</a>
            </div>
            
            <div class="link-group">
              <h4>关注我们</h4>
              <div class="social-links">
                <a href="#"><el-icon><promotion /></el-icon></a>
                <a href="#"><el-icon><chat-dot-square /></el-icon></a>
                <a href="#"><el-icon><connection /></el-icon></a>
              </div>
            </div>
          </div>
        </div>
        
        <div class="footer-bottom">
          <div class="copyright">
            © 2025 图文发布系统 版权所有
          </div>
          <div class="footer-nav">
            <a href="#">使用条款</a>
            <a href="#">隐私政策</a>
            <a href="#">网站地图</a>
          </div>
        </div>
      </div>
    </footer>
    
    <!-- 登录对话框 -->
    <el-dialog
      v-model="loginDialogVisible"
      title="用户登录"
      width="400px">
      <el-form :model="loginForm" label-position="top">
        <el-form-item label="用户名/邮箱">
          <el-input v-model="loginForm.username" placeholder="请输入用户名或邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-button type="primary" class="submit-btn" @click="submitLogin" :loading="loginLoading">登录</el-button>
        <div class="form-footer">
          <div class="forgot-password">
            <a href="#" @click.prevent="showResetPasswordDialog">忘记密码？</a>
          </div>
          还没有账号？ <a href="#" @click.prevent="switchToRegister">立即注册</a>
        </div>
      </el-form>
    </el-dialog>
    
    <!-- 注册对话框 -->
    <el-dialog
      v-model="registerDialogVisible"
      title="用户注册"
      width="400px">
      <el-form :model="registerForm" label-position="top">
        <el-form-item label="用户名">
          <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-button type="primary" class="submit-btn" @click="submitRegister" :loading="registerLoading">注册</el-button>
        <div class="form-footer">
          已有账号？ <a href="#" @click.prevent="switchToLogin">立即登录</a>
        </div>
      </el-form>
    </el-dialog>
    
    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="400px">
      <el-form :model="resetPasswordForm" label-position="top">
        <el-form-item label="用户名">
          <el-input v-model="resetPasswordForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-button type="primary" class="submit-btn" @click="submitResetPassword" :loading="resetPasswordLoading">重置密码</el-button>
        <div class="form-footer">
          记起密码了？ <a href="#" @click.prevent="switchToLogin">返回登录</a>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable vue/multi-word-component-names */
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, ArrowDown, Promotion, ChatDotSquare, Connection } from '@element-plus/icons-vue'
import request from '../utils/request'

// 路由实例
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const isLoggedIn = ref(false)
const username = ref('当前用户')
const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
const userId = ref(null)
const categories = ref([])
const loginDialogVisible = ref(false)
const registerDialogVisible = ref(false)
const loginForm = ref({
  username: '',
  password: '',
  remember: false
})
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})
const loginLoading = ref(false)
const registerLoading = ref(false)
const resetPasswordDialogVisible = ref(false)
const resetPasswordForm = ref({
  username: ''
})
const resetPasswordLoading = ref(false)

// 生命周期钩子
onMounted(() => {
  // 检查用户登录状态
  checkLoginStatus()
  // 获取分类列表
  fetchCategories()
})

// 方法
// 检查登录状态
const checkLoginStatus = async () => {
  // 从本地存储获取用户信息
  const storedUsername = localStorage.getItem('username')

      try {
        const usernameRes = await request.get(`/user/info/${encodeURIComponent(storedUsername)}`)
        
        console.log('0',usernameRes);
        
        if (usernameRes.data.code === '200') {
          const userInfo = usernameRes.data.data
          isLoggedIn.value = true
          username.value = userInfo.username || storedUsername
          userAvatar.value = userInfo.avatarUrl || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
          userId.value = userInfo.id
        } else {
          // 两种方式都失败，清除登录状态
          handleLogout(false) // 传入false表示不调用登出接口
        }
      } catch (error) {
        console.error('通过用户名获取用户信息失败:', error)
        handleLogout(false)
      }
    
  
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/categories/list')
    
    if (res.data.code === '200') {
      categories.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)
      // 加载默认分类数据
      loadDefaultCategories()
    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
    // 加载默认分类数据
    loadDefaultCategories()
  }
}

// 加载默认分类数据
const loadDefaultCategories = () => {
  categories.value = [
    { id: 1, name: '科技' },
    { id: 2, name: '娱乐' },
    { id: 3, name: '体育' },
    { id: 4, name: '国际' },
    { id: 5, name: '财经' },
    { id: 6, name: '教育' },
    { id: 7, name: '文化' },
    { id: 8, name: '动漫' }
  ]
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { q: searchKeyword.value }
    })
    searchKeyword.value = ''
  }
}

const handleCategoryClick = (categoryId) => {
  router.push(`/category/${categoryId}`)
}

const handleLogin = () => {
  loginDialogVisible.value = true
}

const handleRegister = () => {
  registerDialogVisible.value = true
}

const handlePublish = () => {
  router.push('/publish')
}

const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
    router.push({
      name: "UserView",  // 使用 UserView，而不是 User
      params: { id: userId.value },
    });
      break
    case 'settings':
      router.push('/settings')
      break
    case 'messages':
      router.push('/messages')
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogout = async (callLogoutApi = true) => {
  try {
    // 无论请求成功与否，都清除本地存储并更新状态
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('id')
    localStorage.removeItem('rememberMe')
    isLoggedIn.value = false
    username.value = '当前用户'
    userAvatar.value = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    userId.value = null
    
    if (callLogoutApi) {
      ElMessage.success('已退出登录')
    }
    
    // 如果当前页面需要登录权限，则跳转到首页
    if (router.currentRoute.value.path.includes('/user/') || 
        router.currentRoute.value.path === '/publish' ||
        router.currentRoute.value.path === '/settings' ||
        router.currentRoute.value.path === '/messages') {
      router.push('/')
    }
  } catch (error) {
    console.error('登出失败:', error)
  } 
}

const switchToRegister = () => {
  loginDialogVisible.value = false
  registerDialogVisible.value = true
}

const switchToLogin = () => {
  registerDialogVisible.value = false
  loginDialogVisible.value = true
}

const showResetPasswordDialog = () => {
  loginDialogVisible.value = false
  resetPasswordDialogVisible.value = true
}

const submitLogin = async () => {
  // 表单验证
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  
  loginLoading.value = true
  try {
    // 调用登录接口
    const res = await request.post('/user/login', {
      username: loginForm.value.username,
      password: loginForm.value.password
    })
    
    if (res.data.code === '200' || res.data.code === 200) {
      // 登录成功，保存token和用户名
      const userData = res.data.data
      
      // 存储token和用户名
      localStorage.setItem('token', userData.token)
      localStorage.setItem('username', userData.username || loginForm.value.username)
      localStorage.setItem('id', userData.id)
      
      if (loginForm.value.remember) {
        // 如果选择了记住我，可以设置额外标记
        localStorage.setItem('rememberMe', 'true')
      }
      
      // 更新登录状态
      isLoggedIn.value = true
      username.value = userData.username || loginForm.value.username
      
      // 如果返回了用户ID和头像，也直接更新
      if (userData.id) {
        userId.value = userData.id
      }
      
      if (userData.avatar) {
        userAvatar.value = userData.avatar
      }
      
      // 如果需要获取完整用户信息
      if (!userData.id || !userData.avatar) {
        await checkLoginStatus()
      }
      
      // 关闭登录框
      loginDialogVisible.value = false
      // 清空表单
      loginForm.value = {
        username: '',
        password: '',
        remember: false
      }
      
      ElMessage.success('登录成功')
    } else {
      ElMessage.error(res.data.msg || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录请求失败:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loginLoading.value = false
  }
}

const submitRegister = async () => {
  // 表单验证
  if (!registerForm.value.username || !registerForm.value.email || !registerForm.value.password) {
    ElMessage.warning('请填写完整的注册信息')
    return
  }
  
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  registerLoading.value = true
  try {
    // 调用注册接口
    const res = await request.post('/user/register', {
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password
    })
    
    if (res.data.code === '200') {
      // 注册成功
      registerDialogVisible.value = false
      // 清空表单
      registerForm.value = {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
      
      ElMessage.success('注册成功，请登录')
      // 打开登录框
      loginDialogVisible.value = true
    } else {
      ElMessage.error(res.data.msg || '注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('注册请求失败:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    registerLoading.value = false
  }
}

const submitResetPassword = async () => {
  // 表单验证
  if (!resetPasswordForm.value.username) {
    ElMessage.warning('请输入用户名')
    return
  }
  
  resetPasswordLoading.value = true
  try {
    // 调用重置密码接口
    const res = await request.post('/user/reset', {
      username: resetPasswordForm.value.username
    })
    
    if (res.data.code === '200') {
      // 重置密码成功
      resetPasswordDialogVisible.value = false
      // 清空表单
      resetPasswordForm.value = {
        username: ''
      }
      
      ElMessage.success('密码重置成功，新密码是：123456')
      // 打开登录框
      loginDialogVisible.value = true
    } else {
      ElMessage.error(res.data.msg || '重置密码失败，请检查用户名是否正确')
    }
  } catch (error) {
    console.error('重置密码请求失败:', error)

  } finally {
    resetPasswordLoading.value = false
  }
}
</script>

<style scoped>
.app-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 头部样式 */
.app-header {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  text-decoration: none;
  margin-right: 30px;
}

.logo-img {
  width: 36px;
  height: 36px;
  margin-right: 8px;
}

.site-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.main-nav {
  display: flex;
  align-items: center;
}

.nav-link {
  padding: 0 15px;
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: center;
  text-decoration: none;
}

.nav-link:hover {
  color: #409eff;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-box {
  margin-right: 15px;
}

.search-input {
  width: 200px;
}

.search-icon {
  cursor: pointer;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  font-size: 15px;
}

/* 主要内容区域 */
.app-main {
  flex: 1;
  background-color: #f5f7fa;
}

/* 底部样式 */
.app-footer {
  background-color: #2c3e50;
  color: #fff;
  padding: 40px 0 20px;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
}

.footer-logo {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.footer-logo .logo-img {
  width: 50px;
  height: 50px;
  margin-bottom: 10px;
}

.footer-logo .site-name {
  font-size: 18px;
  font-weight: bold;
}

.footer-links {
  display: flex;
  gap: 40px;
}

.link-group h4 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
}

.link-group a {
  display: block;
  color: #ccc;
  margin-bottom: 10px;
  text-decoration: none;
  font-size: 14px;
}

.link-group a:hover {
  color: #fff;
}

.social-links {
  display: flex;
  gap: 15px;
}

.social-links a {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.social-links a:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.footer-bottom {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-nav a {
  color: #ccc;
  text-decoration: none;
  margin-left: 20px;
  font-size: 14px;
}

.footer-nav a:hover {
  color: #fff;
}

/* 表单样式 */
.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forget-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.submit-btn {
  width: 100%;
  margin-bottom: 15px;
}

.form-footer {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

.form-footer a {
  color: #409eff;
  text-decoration: none;
}

.forgot-password {
  text-align: right;
  margin-bottom: 10px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .header-container {
    flex-direction: column;
    height: auto;
    padding: 15px;
  }
  
  .header-left, .header-right {
    width: 100%;
    margin-bottom: 15px;
  }
  
  .logo {
    margin-bottom: 10px;
  }
  
  .main-nav {
    justify-content: space-between;
    width: 100%;
  }
  
  .search-box {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .user-actions {
    justify-content: flex-end;
    width: 100%;
  }
  
  .footer-content {
    flex-direction: column;
  }
  
  .footer-logo {
    margin-bottom: 30px;
  }
  
  .footer-links {
    flex-direction: column;
    gap: 20px;
  }
  
  .footer-bottom {
    flex-direction: column;
    gap: 15px;
  }
  
  .footer-nav a {
    margin: 0 10px;
  }
}
</style> 